// #ifdef MP
import { fs, localPath } from './config'

/**
 * 判断文件/路径是否存在
 * @param path 文件/路径
 */
const isExist = (path: string) =>
  new Promise<boolean>((resolve, reject) => {
    fs
      ? fs?.access({ path, success: () => resolve(true), fail: () => resolve(false) })
      : reject('文件系统不可用')
  })

/**
 * 清理资源
 */
const clearSource = async () => {
  const exist = await isExist(localPath)

  exist && fs?.rmdirSync(localPath, true)
  fs?.mkdirSync(localPath, true)
}

/**
 * 下载文件
 * @param url 链接
 * @param reload 二次加载
 */
const download = async (
  url: string,
  reload = false,
  taskCallback?: (task: UniApp.DownloadTask) => void,
  clearCallback?: () => void,
): Promise<string> => {
  const fileName = url.split('/').pop()
  const filePath = `${localPath}/${fileName}`

  try {
    const exist = await isExist(filePath)

    !exist &&
      (await new Promise((resolve, reject) => {
        const task = uni.downloadFile({ url, filePath, success: resolve, fail: reject })

        taskCallback?.(task)
      }))

    return filePath
  } catch (err: any) {
    // {"errno": 603300, "errMsg": "downloadFile:fail fail:the maximum size of the file storage limit is exceeded"}
    // No such file
    // console.error(err)

    if (!reload) {
      await clearSource()
      clearCallback?.()

      return await download(url, true, taskCallback, clearCallback)
    }

    return ''
  }
}

export { clearSource, download }

// #endif
